package com.rqf.ls.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rqf.ls.service.ILoginOfLawyerService;
import com.rqf.ls.service.IRegisterOfLawyerService;
import com.rqf.ls.service.IVerifyOfLawyerService;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;

/**
 * 律师登录相关
 * @author ServerZhang
 * @date 2016年3月28日
 */
@Controller
@RequestMapping("login/lawyer")
public class LoginOfLawyerController {
	
	@Autowired
	private IRegisterOfLawyerService registerService;
	@Autowired
	private ILoginOfLawyerService loginService;
	@Autowired
	private IVerifyOfLawyerService verifyService;
	
	 /**
	 * 登录方式一：
	 * 支持账号、昵称、手机号+密码方式登录
	 * @param request
	 * @param response
	 * @param name
	 * @param password
	 * @author ServerZhang
	 * @date 2016年3月28日
	 */
	@RequestMapping("byPwd/{name}/{password}")
	public void byPwd(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String name,
			@PathVariable String password){
		Map<String, Object> loginMap = loginService.login(name, password);
		
		OutputUtil.returnJsonp(request, response, JSONSerielizer.toJson(loginMap, null, null));
		//OutputUtil.returnString(response, phoneNo);
	}
	 
	/**
	 * 发送手机验证码
	 * @param response
	 * @param phoneNo
	 * @author ServerZhang
	 * @date 2016年3月28日
	 */
	@RequestMapping("sendCode/{phoneNo}")
	public void sendCode(HttpServletResponse response,
			@PathVariable String phoneNo) {

		String sendCode = registerService.sendCode(phoneNo);
		if (!StringUtils.isEmpty(sendCode)) {
			// 将验证码及发送时间缓存到服务器内存当中
			verifyService.addLoginCode(phoneNo, sendCode);
		} else {
		}
	}
		
	 /**
	 * 登录方式二：
	 * 通过接收手机验证码登录
	 * @param request
	 * @param response
	 * @param phoneNo
	 * @param code
	 * @author ServerZhang
	 * @date 2016年3月28日
	 */
	@RequestMapping("byCode/{phoneNo}/{code}")
	public void byCode(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String phoneNo,
			@PathVariable String code){
		Boolean isSuccess = false;
		Map<String, Object> updateCode = verifyService.getLoginCode(phoneNo);
		if (updateCode != null) {
			Object codeObj = updateCode.get("code");
			if (code.equals(codeObj)) {
				isSuccess = true;
			}
		}
		if (isSuccess) {
			verifyService.deleteLoginCode(phoneNo);
			OutputUtil.returnString(response, phoneNo);
		}else {
			OutputUtil.returnString(response, "");
		}
	}
}
